package com.xianggu.designMode.decorator.demo02;

import java.io.*;

/**
 * @author chengjy
 * @date 2025/3/19
 */
public class BufferWriteFile extends FileOutputStream {

    private final byte[] buffer;
    private int size = 0;

    public BufferWriteFile(int size, File file) throws FileNotFoundException {
        super(file);
        this.buffer = new byte[size];
    }

    @Override
    public void write(int b) throws IOException {
        // 判断是否可写数据
        if (isWriteable()) {
            // 写入到缓冲区
            bufferWriteData(b);
            return;
        }
        // 刷新缓冲区
        refreshBuffer();
        // 写入到缓冲区
        bufferWriteData(b);
    }

    private void bufferWriteData(int b) {
        buffer[size++] = (byte) b;
    }

    private void refreshBuffer() {
        try {
            super.write(buffer, 0, size);
            // 重置游标
            size = 0;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean isWriteable() {
        // 指标越界
        if(size >= buffer.length){
            return false;
        }
        // 缓存中无数据
        return true;
    }
}
